package com.hps.spring.cloud.alibaba.controller;

import javax.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


/**
 * @author heps
 * @since 2020/11/4 13:56
 */
@RestController
@RequestMapping("/user")
public class AuthController {

  @Resource
  private LoadBalancerClient loadBalancerClient;

  @RequestMapping("/login")
  public Object login(String username, String password) {
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>();
    formParams.set("username", username);
    formParams.set("password", password);
    formParams.set("grant_type", "password");
    formParams.set("scope", "server");
    formParams.set("client_id", "client_2");
    formParams.set("client_secret", "123456");
    ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-auth-server");
    String url = String.format("http://%s:%s/uaa/oauth/token",serviceInstance.getHost(), serviceInstance.getPort());
    return restTemplate.postForEntity(url, formParams, OAuth2AccessToken.class).getBody();
  }
}
